package com.situ.gym.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.situ.gym.pojo.dto.UserLoginDTO;
import com.situ.gym.pojo.dto.UserPasswordDTO;
import com.situ.gym.pojo.entity.User;
import com.situ.gym.pojo.entity.User;
import com.situ.gym.pojo.query.UserQuery;
import com.situ.gym.service.IUserService;
import com.situ.gym.service.IUserService;
import com.situ.gym.util.JwtUtil;
import com.situ.gym.util.Result;
import com.situ.gym.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Gao
 * @since 2025-05-08
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("/list")
    public Result list(UserQuery userQuery) {
        System.out.println("UserController.list");
        IPage<User> page = userService.list(userQuery);
        return Result.ok(page);
    }

    // /user/deleteById?id=12
    // /user/deleteById/12
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        userService.removeById(id);
        return Result.ok("删除成功");
    }

    // /user/deleteById/1,2,3
    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Integer[] ids) {
        userService.removeBatchByIds(Arrays.asList(ids));
        return Result.ok("删除成功");
    }

    // @RequestBody : 封装前台传递过来的JSON格式数据
    // @ResponseBody : 将数据转换为JSON格式返回
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        userService.save(user);
        return Result.ok("添加成功");
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        User user = userService.getById(id);
        return Result.ok(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateById(user);
        return Result.ok("修改成功");
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO) {
        //首先判断验证码是否正确
        String captcha = (String) redisTemplate.opsForValue().get("captcha:" + userLoginDTO.getUuid());
        if (ObjectUtils.isEmpty(captcha)) {
            return Result.error("验证码已经失效");
        }
        if (!captcha.equalsIgnoreCase(userLoginDTO.getCaptcha())) {
            return Result.error("验证码错误");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", userLoginDTO.getName());
        User loginUser = userService.getOne(queryWrapper);
        //判断用户名是否存在
        if (ObjectUtils.isEmpty(loginUser)) {
            return Result.error("用户名不存在");
        }

        //判断密码是否正确
        if (!loginUser.getPassword().equalsIgnoreCase(userLoginDTO.getPassword())) {
            return Result.error("密码错误");
        }

        //登录成功
        Map<String, Object> map = new HashMap<>();
        map.put("id", loginUser.getId());
        map.put("name", loginUser.getName());
        String token = JwtUtil.createToken(map);
        return Result.ok("登录成功", token);

    }

    @GetMapping("/userInfo")
    public Result userInfo(@RequestHeader(name = "Authorization") String token) {
        Map<String, Object> map = JwtUtil.parseToken(token);
        Integer id = (Integer) map.get("id");
        User user = userService.getById(id);
        return Result.ok(user);
    }

    @PutMapping("/resetPassword")
    public Result resetPassword(@RequestBody UserPasswordDTO userPasswordDTO,
                                @RequestHeader(name = "Authorization") String token) {
        //Map<String, Object> map = JwtUtil.parseToken(token);
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        User user = userService.getById(id);
        if (!user.getPassword().equalsIgnoreCase(userPasswordDTO.getOldPassword())) {
            return Result.error("旧密码错误");
        }

        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("password", userPasswordDTO.getNewPassword());
        userService.update(user, updateWrapper);
        return Result.ok("更新成功");
    }
}

